<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>好好吃蛋糕店登录界面</title><!DOCTYPE html>
      <html>

      <head>
      <meta http-equiv="content-type" content="text/html; charset=utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">

      
  <link rel="stylesheet" href="style.css">
</head>

<body>
<div class="container">
  <div class="form-box">
    <!-- 登录 -->
    <div class="login-box">
      <h1>login</h1>
      <input type="text" id="username_log" placeholder="用户名">
      <input type="password" id="password_log" placeholder="密码">
      <button id="loginButton">登录</button>
    </div>
  </div>
  <div class="con-box right">
    <h2><span>好好吃面包店管理系统</span></h2>
    <img src="images/register.jpg" alt="">
    <p>切换客户登录</p>
    <button id="returnButton">返回</button>
  </div>
</div>

<script>
  // 使用新的 ID 获取返回按钮
  let returnButton = document.getElementById('returnButton');
  let loginButton = document.getElementById('loginButton');

  // 返回按钮点击事件
  returnButton.addEventListener('click', () => {
    window.location.href = 'index.html';
  });

  loginButton.addEventListener('click', function(event) {
    event.preventDefault();

    const loginEmail = document.getElementById('username_log').value.trim();
    const loginPassword = document.getElementById('password_log').value.trim();

    if (!loginEmail || !loginPassword) {
      alert('邮箱和密码不能为空。');
      return;
    }

    const loginData = {
      email: loginEmail,
      password: loginPassword
    };

    fetch('/api/users/admin/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(loginData)
    })
            .then(response => {
              if (!response.ok) {
                throw new Error('Network response was not ok');
              }
              return response.json();
            })
            .then(data => {
              console.log('Response data:', data); // 打印完整的响应数据
              // 检查响应数据中是否包含token和userId
              if (data && data.token && data.userId) {
                alert('登录成功！');
                console.log('登录人信息：', data);

                // 将JWT存储在Cookie中
                document.cookie = `auth_token=${data.token}; path=/; secure; HttpOnly; SameSite=Strict`;

                // 重定向到受保护的页面
                window.location.href = '/adminview/admin.html';
              } else {
                alert('登录失败，未收到有效的认证信息。');
              }
            })
            .catch(error => {
              alert('登录失败，请重试。');
              console.error('Error:', error);
            });
  });
</script>
</body>

</html>
</head>
<body>

</body>
</html>